package com.wg.wuge.tulin.rocketmq;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.remoting.exception.RemotingTooMuchRequestException;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

public class RocketMqDemo {

    public static void main(String[] args) throws MQClientException, InterruptedException,
            MQBrokerException, RemotingException, UnsupportedEncodingException {
        DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
        producer.setNamesrvAddr("192.168.64.2:9876");
        producer.setClientIP("192.168.64.1");
        producer.setRetryTimesWhenSendFailed(3);  // 设置重试次数
        producer.setSendMsgTimeout(10000); // Set timeout to 10 seconds (adjust as needed)

        // 打印 NameServer 地址
        System.out.println("NameServer Address: " + producer.getNamesrvAddr());

        producer.start();
        // 等待几秒，防止生产者启动未完成就发送消息
        TimeUnit.SECONDS.sleep(3);
        try {
            for (int i = 0; i < 1; i++) {
                Message msg = new Message("TopicTest_TagA", ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
                SendResult sendResult = producer.send(msg);
                System.out.printf("%s%n", sendResult);
            }
        } catch (RemotingTooMuchRequestException e) {
            // Handle the exception, e.g., implement retry logic or log the error
            System.err.println("Sending message failed due to RemotingTooMuchRequestException: " + e.getMessage());
            e.printStackTrace();
        }

        producer.shutdown();
    }
}
